<?php

namespace Xin\Hint\Laravel;

use Illuminate\Foundation\Application as LaravelApplication;
use Illuminate\Support\ServiceProvider;
use Laravel\Lumen\Application as LumenApplication;
use Xin\Hint\Contracts\Factory as HintFactory;
use Xin\Hint\HintHandler;
use Xin\Hint\HintManager;

class HintServiceProvider extends ServiceProvider
{
	/**
	 * Register any application services.
	 *
	 * @return void
	 */
	public function register()
	{
		if ($this->app instanceof LumenApplication) {
			$this->app->configure('hint');
		}

		$this->registerManager();
		$this->registerScenes();
	}

	/**
	 * 注册提示管理器
	 * @return void
	 */
	protected function registerManager()
	{
		$this->app->singleton(HintManager::class, function ($app) {
			return new HintManager(config('hint') ?: []);
		});
		$this->app->alias(HintManager::class, 'hint');
		$this->app->alias(HintManager::class, HintFactory::class);

		$this->app->singleton('hint.driver', function ($app) {
			return $app['hint']->hint();
		});
	}

	/**
	 * 注册提示器场景
	 */
	protected function registerScenes()
	{
		/** @var HintManager $manager */
		$manager = $this->app['hint'];

		// extend api hint
		$manager->extend('api', function ($name, $config) use ($manager) {
			return new HintHandler($manager->newHintHandlerConfig($config), new ApiRender());
		});
	}

	/**
	 * Register the config for publishing
	 *
	 */
	public function boot()
	{
		if ($this->app instanceof LaravelApplication && $this->app->runningInConsole()) {
			$this->publishes([$this->configPath() => config_path('hint.php')], 'hint');
		}
	}

	/**
	 * Set the config path
	 *
	 * @return string
	 */
	protected function configPath()
	{
		return __DIR__ . '/../../config.php';
	}
}
